package com.hdu.seckilldemo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hdu.seckilldemo.pojo.Order;
import com.hdu.seckilldemo.pojo.SeckillMessage;
import com.hdu.seckilldemo.pojo.SeckillOrder;
import com.hdu.seckilldemo.pojo.User;
import com.hdu.seckilldemo.rabbitmq.MQSender;
import com.hdu.seckilldemo.service.IGoodsService;
import com.hdu.seckilldemo.service.IOrderService;
import com.hdu.seckilldemo.service.ISeckillGoodsService;
import com.hdu.seckilldemo.service.ISeckillOrderService;
import com.hdu.seckilldemo.service.impl.SeckillOrderServiceImpl;
import com.hdu.seckilldemo.utils.JsonUtil;
import com.hdu.seckilldemo.vo.GoodsVo;
import com.hdu.seckilldemo.vo.RespBean;
import com.hdu.seckilldemo.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/seckill")
public class SecKillController implements InitializingBean {
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private ISeckillOrderService seckillOrderService;
    @Autowired
    private IOrderService orderService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MQSender mqSender;
    //添加内存标记
    private Map<Long,Boolean> EmptyStockMap = new HashMap<>();
    @Autowired
    private RedisScript<Long> script;

    /**
     *  秒杀接口
     * @param model
     * @param user
     * @param goodsId
     * @return
     */
    @RequestMapping(value = "/doSeckill",method =  RequestMethod.POST)
    @ResponseBody
    public RespBean doSecKill(Model model, User user, Long goodsId){
        if(user == null){
            return RespBean.error(RespBeanEnum.SESSION_ERROR);
        }
        ValueOperations valueOperations = redisTemplate.opsForValue();

        //1. 检查一人一单（重复购买）
        // 优化2: 使用redis 优化重复订单的查询速度(在每次秒杀以后，会将订单信息写入redis,后续的重复请求会从redis中找数据)
        SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.opsForValue().get("order:"+user.getId()+":"+goodsId);
        if(seckillOrder != null){
            //如果多次下单 返回异常
            return RespBean.error(RespBeanEnum.REPEATE_ERROR);
        }
        //内存标记 减少Redis访问量
        if(EmptyStockMap.get(goodsId)){
            //没有库存了 返回错误
            return RespBean.error(RespBeanEnum.EMPTY_STOCK);
        }
        //2. 预减库存操作 该方法为原子类型的 没有线程安全问题
        // 优化 将减库存操作 通过lua脚本实现
        //Long stock = valueOperations.decrement("seckillGoods:" + goodsId);
        Long stock = (Long)redisTemplate.execute(script, Collections.singletonList("seckillGoods:"+goodsId),Collections.EMPTY_LIST);
        if(stock == 0){
            // 标记库存已经抢完
            EmptyStockMap.put(goodsId,true);
            ///原子性加一避免负数情况出现 (用lua脚本就不用考虑了)
            //valueOperations.increment("seckillGoods:"+goodsId);
            //库存不足 返回错误
            return RespBean.error(RespBeanEnum.EMPTY_STOCK);
        }

        //3. 创建订单
        //优化4： 使用rabbitMQ 将添加订单操作异步出去，进行*流量削峰*
        SeckillMessage seckillMessage = new SeckillMessage(user,goodsId);
        //往消息队列发送消息
        mqSender.send_Seckill_order(JsonUtil.object2JsonStr(seckillMessage));
        //消息消费模块在MQReceiver.java
        return RespBean.success(0);
    }

    /**
     *  redis优化前：
     *     @RequestMapping(value = "/doSeckill",method =  RequestMethod.POST)
     *     @ResponseBody
     *     public RespBean doSecKill(Model model, User user, Long goodsId){
     *         if(user == null){
     *             return RespBean.error(RespBeanEnum.SESSION_ERROR);
     *         }
     *         //从sql中查找商品详情信息
     *         GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);
     *         //1. 判断库存
     *         if(goodsVo.getStockCount() < 1){
     *             return RespBean.error(RespBeanEnum.EMPTY_STOCK); //库存不足，秒杀失败
     *         }
     *         //2. 检查一人一单（重复购买）
     *         //SeckillOrder seckillOrder = seckillOrderService.getOne(new QueryWrapper<SeckillOrder>().eq("user_id",user.getId()).eq("goods_id",goodsId));
     *         // 优化2: 使用redis 优化重复订单的查询速度(在每次秒杀以后，会将订单信息写入redis,后续的重复请求会从redis中找数据)
     *         SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.opsForValue().get("order:"+user.getId()+":"+goodsVo.getId());
     *         if(seckillOrder != null){
     *             //如果多次下单 返回异常
     *             return RespBean.error(RespBeanEnum.REPEATE_ERROR);
     *         }
     *         //3. 创建订单
     *
     *         Order order = orderService.seckill(user,goodsVo); // 超卖： 给订单数据库添加一个goods_id和user_id的UNIQUE索引
     *
     *         return RespBean.success(order);
     *     }
     */

    /**
     * 系统初始化，把商品库存加载到redis
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        List<GoodsVo> list = goodsService.findGoodsVo();
        // 如果商品列表为空 就不加载
        if(CollectionUtils.isEmpty(list)){
            log.info("加载商品列表失败/或者商品列表为空");
            return;
        }
        //将每条数据作为 seckillGoods:id  stockCount 写入Redis
        list.forEach(goodsVo ->{
            //1.将商品数量添加到redis中去
            redisTemplate.opsForValue().set("seckillGoods:"+goodsVo.getId(),goodsVo.getStockCount());
            //2. <Key-Value> <商品Id-库存情况>（false为有库存，true为无）
            if (goodsVo.getStockCount() > 0)
                EmptyStockMap.put(goodsVo.getId(), false);
            else
                EmptyStockMap.put(goodsVo.getId(), true);
        });
    }

    /**
     * 获取秒杀结果
     * @param user
     * @param goodsId
     * @return -1：秒杀失败；0排队中；orderId 成功
     */
    @RequestMapping(value = "/result",method = RequestMethod.GET)
    @ResponseBody
    public RespBean getResult(User user, Long goodsId){
        if(user == null){
            //验证用户失败
            return RespBean.error(RespBeanEnum.SESSION_ERROR);
        }
        //查询秒杀订单结果
        Long orderId = seckillOrderService.getResult(user,goodsId);
        return RespBean.success(orderId);

    }
}
